//
//  LocationServeViewController.m
//  EasyToTesco2.0
//
//  Created by baozi on 16/8/19.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "LocationServeViewController.h"
#import "ReadWriteLocationCity.h"
#import "LocationServeManager.h"
#import "HotCityTableViewCell.h"

@interface LocationServeViewController ()<UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate,didClickHotCityButtonDelegate>

{
    NSString *_locationCityString;
}

@property (nonatomic, strong) NSMutableDictionary *cities;

@property (nonatomic, strong) NSMutableArray *keys; //城市首字母
@property (nonatomic, strong) NSMutableArray *arrayCitys;   //城市数据
@property (nonatomic, strong) NSMutableArray *arrayHotCity;

@property(nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong) UILabel *locationLabel;

@end

@implementation LocationServeViewController

- (void)setUpLocationServeNavigationBar {
    
    self.navigationController.navigationBar.backgroundColor = DEFAULT_COLOR;
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"jiantou"] highImage:[UIImage imageNamed:@"jiantou"] target:self action:@selector(backToHomeController) forControlEvents:UIControlEventTouchUpInside title:nil];
    self.navigationItem.leftBarButtonItem.imageInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    
    
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    [customLab setTextColor:[UIColor whiteColor]];
    customLab.textAlignment = NSTextAlignmentCenter;
    [customLab setText:@"选择城市"];
    customLab.font = [UIFont boldSystemFontOfSize:18];
    self.navigationItem.titleView = customLab;
}

- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
        self.arrayHotCity = [NSMutableArray arrayWithObjects:@"长沙",@"杭州",@"北京",@"上海",@"广州", nil];
        self.keys = [NSMutableArray array];
        self.arrayCitys = [NSMutableArray array];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSLog(@"%s",__func__);
}

- (void)applicationFinishedRestoringState {
    NSLog(@"%s",__func__);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%@",[ReadWriteLocationCity ReadLocationString]);
    [self getCityData];
    
    // Do any additional setup after loading the view.
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
    
    [self setUpFirstCellType];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setUpLocationServeNavigationBar];
    
    if ([CLLocationManager locationServicesEnabled] &&
        ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse
         || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
            //定位功能可用，开始定位
            NSString *cityString = [ReadWriteLocationCity ReadLocationString];
            self.locationLabel.text = [NSString stringWithFormat:@"%@",cityString];
            self.locationLabel.frame = CGRectMake(16, 8, (WIDTH - 64) / 3, 30);
        }
    else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
        self.locationLabel.frame = CGRectMake(16, 8, 150, 30);
        self.locationLabel.text = @"定位失败,请点击重试";
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ComeBackAppWithSetting) name:@"locationCity" object:nil];
}

- (void)ComeBackAppWithSetting {
    if ([CLLocationManager locationServicesEnabled] &&
        ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse
         || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
            //定位功能可用，开始定位
            NSString *cityString = [ReadWriteLocationCity ReadLocationString];
            self.locationLabel.text = [NSString stringWithFormat:@"%@",cityString];
            self.locationLabel.frame = CGRectMake(16, 8, (WIDTH - 64) / 3, 30);
        }
    else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
        self.locationLabel.frame = CGRectMake(16, 8, 150, 30);
        self.locationLabel.text = @"定位失败,请点击重试";
    }

}

#pragma mark 城市定位逻辑
- (void)setUpFirstCellType {
    self.locationLabel = [[UILabel alloc] init];
    self.locationLabel.font = [UIFont systemFontOfSize:14];
    self.locationLabel.textAlignment = NSTextAlignmentCenter;
    self.locationLabel.layer.borderWidth = 0.5;
    self.locationLabel.backgroundColor = [UIColor whiteColor];
    self.locationLabel.layer.borderColor = [UIColor grayColor].CGColor;
    
    self.locationLabel.layer.cornerRadius = 3;
    self.locationLabel.layer.masksToBounds = YES;
    
    NSLog(@"%@",[ReadWriteLocationCity ReadLocatinoCity]);
    
}

#pragma mark TableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
    
        if ([self.locationLabel.text isEqualToString:@"定位失败,请点击重试"]) {
            [self JudgeGoToSettingAlertViewController];
        } else {
            [ReadWriteLocationCity saveLocationCity:[ReadWriteLocationCity ReadLocationString]];
            
            [self backToHomeController];
        }
        
    } else {
        NSString *key = [_keys objectAtIndex:indexPath.section];
        
        [ReadWriteLocationCity saveLocationCity:[[_cities objectForKey:key] objectAtIndex:indexPath.row]];
        
        [self backToHomeController];
    }
}

#pragma mark 跳转设置逻辑

- (void)dealloc {
    [LocationServeManager sharedLocationServeManager].delegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"locationCity" object:nil];
}

- (void)JudgeGoToSettingAlertViewController {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"定位服务未开启" message:@"请在系统设置中开启定位服务" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        
        if([[UIApplication sharedApplication] canOpenURL:url]) {
            
            NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication] openURL:url];
            
        }
    }];
    [alert addAction:SettingAction];
    
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancelAction];
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 获取城市数据
-(void)getCityData
{
    NSString *path=[[NSBundle mainBundle] pathForResource:@"citydict"
                                                   ofType:@"plist"];
    self.cities = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    
    [self.keys addObjectsFromArray:[[self.cities allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    
    
    NSString *location = @"定";
    [self.keys insertObject:location atIndex:0];
    
    //添加热门城市
    NSString *strHot = @"热";
    [self.keys insertObject:strHot atIndex:1];
    [self.cities setObject:_arrayHotCity forKey:strHot];
    
}

- (void)didClickHotCityButton:(UIButton *)button {
    [ReadWriteLocationCity saveLocationCity:self.arrayHotCity[button.tag]];
    
    [self backToHomeController];
}

#pragma mark - tableView
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
    bgView.backgroundColor = BACKGROUND_COLOR;
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(13, 0, 250, 20)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont systemFontOfSize:12];
    
    NSString *key = [_keys objectAtIndex:section];
    
//    if ([key rangeOfString:@"!"].location != NSNotFound) {
//        titleLabel.text = @"定位城市";
//    }
    
    titleLabel.text = key;
    
    if ([key rangeOfString:@"热"].location != NSNotFound || section == 1) {
        titleLabel.text = @"热门城市";
    }
    
    if([key rangeOfString:@"定"].location != NSNotFound) {
        titleLabel.text = @"定位城市";
        
    }
    
    [bgView addSubview:titleLabel];
    
    return bgView;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return _keys;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [_keys count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 1;
    } else {
        NSString *key = [_keys objectAtIndex:section];
        NSArray *citySection = [_cities objectForKey:key];
        return [citySection count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        UITableViewCell *first = [tableView dequeueReusableCellWithIdentifier:@"first"];
        
        if (!first) {
            first = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"first"];
            first.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        first.contentView.backgroundColor = BACKGROUND_COLOR;
        [first.contentView addSubview:self.locationLabel];
        
        return first;
        
    } else if (indexPath.section == 1) {
        HotCityTableViewCell *hotCity = [[HotCityTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HotCity"];
        hotCity.delegate = self;
        hotCity.HotCityArray = self.arrayHotCity;
        hotCity.contentView.backgroundColor = BACKGROUND_COLOR;
        return hotCity;
        
    } else {
        static NSString *CellIdentifier = @"Cell";
        NSString *key = [_keys objectAtIndex:indexPath.section];
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
            cell.backgroundColor = [UIColor clearColor];
            cell.contentView.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [cell.textLabel setTextColor:[UIColor blackColor]];
            cell.textLabel.font = [UIFont systemFontOfSize:18];
        }
        cell.textLabel.text = [[_cities objectForKey:key] objectAtIndex:indexPath.row];
        UIView *bottomLineView = [[UIView alloc] init];
        bottomLineView.backgroundColor = BACKGROUND_COLOR;
        [bottomLineView setFrame:CGRectMake(16, 43, WIDTH - 32, 1)];
        [cell.contentView addSubview:bottomLineView];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 46;
    }  else if (indexPath.section == 1) {
        return 94;
    } else {
        return 44;
    }
}

/**
 *  返回按钮点击方法
 */
- (void)backToHomeController {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
